import Taro, { Component } from '@tarojs/taro';
import { View, Text,Input } from '@tarojs/components'
import "./search.scss"
import Historylist from './historylist'
import Searchlist from './searchlist'
import {post} from '../../utils/http'

class search extends Component {

  constructor() {
    this.state = {
      keyword: '',
      datalist: [],
      historylist: Taro.getStorageSync('historylist') || [],
      showHistory: true
    }
  }


  inputChange(event) {
    console.log(event)
    this.setState({
      keyword: event.target.value
    })
  }

  async handleSearch() {
    console.log(this.state.keyword);
    let historylist = Taro.getStorageSync('historylist') || [];
    historylist.push(this.state.keyword)
    let list = [...new Set(historylist)]
    Taro.setStorageSync('historylist', list)
    this.setState({
      showHistory: false
    })
    Taro.showLoading()
    let rs = await post('index.php/trade/get_search_list', {
      keyword: this.state.keyword
    })
   
    this.setState({
      datalist: rs.data
    })
    Taro.hideLoading()
  }

  searchByHistory=(keyword)=>{
    console.log(keyword)
    this.setState({
      keyword
    },()=>{
      this.handleSearch();
    })
  }


  render() {
    return (
      <View>
        <View class="searchForm">
          <Input placeholder="请输入关键字" onInput={this.inputChange}></Input>
          <Text onClick={this.handleSearch}>搜索</Text>
        </View>

        {
          this.state.showHistory ?
            <Historylist itemClick={this.searchByHistory} datalist={this.state.historylist}></Historylist> :
            <Searchlist datalist={this.state.datalist}></Searchlist>
        }
      </View >
    );
  }
}

export default search;